# encoding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from cgi import escape
import io

def _write(output_stream, dom):
    #TODO: Make the output prettier.
    if dom.type == 'root':
        for node in dom.children:
            _write(output_stream, node)
    elif dom.type == 'paragraph':
        output_stream.write('<p>\n')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</p>\n')
    elif dom.type == 'block quote':
        output_stream.write('<blockquote>\n')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</blockquote>\n')
    elif dom.type == 'list item':
        output_stream.write('<li>\n')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</li>\n')
    elif dom.type == 'unordered list':
        output_stream.write('<ul>\n')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</ul>\n')
    elif dom.type == 'ordered list':
        output_stream.write('<ol>\n')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</ol>\n')
    elif dom.type == 'header':
        tag = 'h{0}'.format(header.level)
        output_stream.write('<{0}>\n'.format(tag))
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</{0}>\n'.format(tag))
    elif dom.type == 'nbsp':
        output_stream.write('&nbsp;')
    elif dom.type == 'ellipsis':
        output_stream.write('&hellip;')
    elif dom.type == 'en dash':
        output_stream.write('&ndash;')
    elif dom.type == 'em dash':
        output_stream.write('&mdash;')
    elif dom.type == 'quote':
        output_stream.write('<q>')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</q>')
    elif dom.type == 'strong':
        output_stream.write('<strong>')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</strong>')
    elif dom.type == 'emphasized':
        output_stream.write('<em>')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</em>')
    elif dom.type == 'code':
        output_stream.write('<code>')
        for node in dom.children:
            _write(output_stream, node)
        output_stream.write('</code>')
    elif dom.type == 'text':
        output_stream.write(escape(dom.text))


def convert(dom):
    with io.StringIO() as output_stream:
        _write(output_stream, dom)
        return output_stream.getvalue()

